<template>
  <div id="managementCenter">
    <a-layout class="layout">
      <a-layout-sider class="left" :width="260">
        <section class="search-box">
          <a-select
            ref="select"
            v-model:value="treeSelectSearchValue"
            style="width: 85px"
          >
            <a-select-option value="room_alias_id">
              {{ $L("房源") + "编号" }}
            </a-select-option>
            <a-select-option value="keywords_1">房号</a-select-option>
            <a-select-option value="keywords_2">
              {{ $L("租客") + "名" }}
            </a-select-option>
            <a-select-option value="keywords_3">手机号</a-select-option>
          </a-select>
          <a-input-search
            v-model:value="treeSearchValue"
            class="search-box-input"
            placeholder="请输入"
            @search="onTreeSearch"
            :allowClear="true"
            enter-button
          />
        </section>

        <section
          class="left-content"
          :style="
            currentType == 'room'
              ? 'height: calc(100% - 20px)'
              : 'padding-bottom: 100px;'
          "
        >
          <section v-if="showSearch">
            <template v-if="searchedList.length">
              <a-list
                :pagination="searchedListPagination"
                :data-source="searchedList"
              >
                <template #renderItem="{ item }">
                  <a-list-item
                    key="item.title"
                    style="cursor: pointer; width: 100%"
                  >
                    <div
                      style="width: 100%; display: flex; align-items: center"
                      @click="onRoomClick(item)"
                    >
                      <cu-icon
                        type="org-tree-fangjian"
                        style="margin-right: 10px; color: #666"
                      />
                      <div class="org-tree-dec">
                        <div :style="{ display: 'flex' }">
                          <span>房间号：</span>
                          <span
                            style="
                              display: inline-block;
                              width: 55%;
                              overflow: hidden;
                              text-overflow: ellipsis;
                              white-space: nowrap;
                            "
                            >{{ item.layer_name }} / {{ item.room_name }}</span
                          >
                        </div>
                        <div>
                          楼宇：{{ item.village_name }} / {{ item.build_name }}
                        </div>
                      </div>
                      <template
                        v-if="
                          item.room_name &&
                          item.contract_info &&
                          item.contract_info.length
                        "
                      >
                        <cu-icon
                          type="org-zukehuaxiang"
                          style="
                            margin-left: 10px;
                            color: #52c41a;
                            font-size: 16px;
                          "
                        />
                      </template>
                    </div>
                  </a-list-item>
                </template>
              </a-list>
            </template>
            <Empty
              v-if="!searchedList.length"
              :image="simpleImage"
              description="没有找到相关内容"
            />
          </section>
          <!-- 树 -->
          <template v-else>
            <VillageTree
              :showRentIcon="true"
              :refreshParams="refreshParams"
              :refreshTrigger="refreshTrigger"
              @getCurrent="getCurrentSelect"
              @rentClick="getCurrentRent"
              @request="$utils.commonRequest"
            />
          </template>
        </section>

        <!-- 底部操作按钮 -->
        <a-card
          size="small"
          :bordered="false"
          class="footer-btn"
          v-if="currentType != 'room'"
        >
          <a-row :gutter="12">
            <template v-if="currentType == 'village'">
              <a-col :span="12" style="text-align: center">
                <a-button
                  v-permission="['villageList', 'curd', 'add']"
                  @click="addVillage"
                >
                  <template #icon>
                    <PlusOutlined />
                  </template>
                  新建项目
                </a-button>
              </a-col>
              <a-col :span="12" style="text-align: center">
                <a-button
                  v-permission="['buildList', 'curd', 'add']"
                  @click="buildingAddVisible = true"
                >
                  <template #icon>
                    <PlusOutlined />
                  </template>
                  新建楼宇
                </a-button>
              </a-col>
            </template>
            <template v-if="currentType == 'build'">
              <a-col :span="12" style="text-align: center">
                <a-button @click="layerAddVisible = true">
                  <template #icon>
                    <PlusOutlined />
                  </template>
                  添加楼层
                </a-button>
              </a-col>
              <a-col :span="12" style="text-align: center">
                <a-button @click="importRoomVisible = true">
                  <template #icon>
                    <UploadOutlined />
                  </template>
                  导入房源
                </a-button>
              </a-col>
            </template>
            <template v-if="currentType == 'layer'">
              <a-col :span="12" style="text-align: center">
                <a-button @click="addRoomVisible = true">
                  <template #icon>
                    <PlusOutlined />
                  </template>
                  新增房源
                </a-button>
              </a-col>
              <a-col :span="12" style="text-align: center">
                <a-button @click="importRoomVisible = true">
                  <template #icon>
                    <UploadOutlined />
                  </template>
                  导入房源
                </a-button>
              </a-col>
            </template>
          </a-row>
        </a-card>
      </a-layout-sider>
      <a-layout-content class="right">
        <VillageInfo
          v-if="currentType == 'village'"
          showType="page"
          :villageId="currentVillageId"
          @remove="onCurrentRemove('village')"
        />

        <BuildInfo
          v-if="currentType == 'build'"
          showType="page"
          :villageId="currentVillageId"
          :buildId="currentBuildId"
          @layerChange="onBuildLayerChange"
          @remove="onCurrentRemove('build')"
          @onChange="onCurrentChange"
        />

        <LayerInfo
          v-if="currentType == 'layer'"
          showType="page"
          :villageId="currentVillageId"
          :layerId="currentLayerId"
          @remove="onCurrentRemove('layer')"
          @onChange="onCurrentChange"
        />
        <RoomInfo
          v-if="currentType == 'room' || currentType == 'subRoom'"
          pageFrom="ManagementCenter"
          showType="page"
          appSuffix="manage"
          :villageId="currentVillageId"
          :buildId="currentBuildId"
          :roomId="currentRoomId"
          :parentRoomId="currentParentRoomId"
          @remove="onCurrentRemove('room')"
          @onChange="onCurrentChange"
        />
      </a-layout-content>
    </a-layout>

    <!-- 新增项目-选择项目类型 -->
    <ChooseVillageType
      :visible="chooseTypeVisible"
      @close="chooseTypeVisible = false"
    />
    <!-- 新增楼宇 -->
    <BuildingAdd
      :visible="buildingAddVisible"
      :villageId="currentVillageId"
      @cancel="buildingAddVisible = false"
      @success="buildingAddVisible = false"
    />
    <!-- 添加楼层 -->
    <LayerAdd
      :visible="layerAddVisible"
      :content="{ villageId: currentVillageId, buildId: currentBuildId }"
      @cancel="layerAddVisible = false"
      @success="handleLayerAddSuccess"
    />
    <!-- 导入房源 -->
    <ImportRoom
      :visible="importRoomVisible"
      @refresh="importRoomSuccess"
      @clear="importRoomVisible = false"
    />
    <!-- 新增房源 -->
    <AddHouse
      v-if="addRoomVisible"
      :visible="addRoomVisible"
      :buildId="currentBuildId"
      :villageId="currentVillageId"
      :layerId="currentLayerId"
      @cancel="addRoomVisible = false"
      @success="handleRoomAddSuccess"
    />
  </div>
</template>

<script>
import { defineComponent, reactive, toRefs, computed, watch } from "vue";
import { Empty } from "ant-design-vue";
import request from "../../../common/utils/request";
import store from "../../../store";
import {
  GoldenFilled,
  PlusOutlined,
  UploadOutlined,
} from "@ant-design/icons-vue";

import { useRouter } from "vue-router";
import { VillageTree } from "bl-common-vue3";
import ChooseVillageType from "../ProjectManage/modules/ChooseVillageType.vue";
import BuildingAdd from "../BuildingManage/modules/BuildingEdit.vue";
import LayerAdd from "../BuildingManage/modules/LayerEdit.vue";
import ImportRoom from "../SpaceManage/modules/Import.vue";
import AddHouse from "../SpaceManage/modules/AddHouse.vue";

// 项目
import VillageInfo from "../../../components/village/VillageInfo.vue";
// 楼宇
import BuildInfo from "../../../components/village/BuildInfo.vue";
// 楼层
import LayerInfo from "../../../components/village/LayerInfo.vue";
// 房源
import RoomInfo from "../../../components/village/RoomInfo.vue";
export default defineComponent({
  name: "managementCenter",
  components: {
    Empty,
    GoldenFilled,
    PlusOutlined,
    UploadOutlined,

    VillageTree,
    ChooseVillageType,
    BuildingAdd,
    LayerAdd,
    ImportRoom,
    AddHouse,

    VillageInfo,
    BuildInfo,
    LayerInfo,
    RoomInfo,
  },
  setup(props, context) {
    const state = reactive({
      treeSearchValue: "",
      treeSelectSearchValue: "room_alias_id", // 默认为房号搜索
      showSearch: false,
      searchedList: [],
      searchedListPage: 1,
      searchedListPageSize: 20,
      searchedListTotal: 0,

      // 树当前选中
      currentSelect: {},
      currentType: props.currentType ? props.currentType : "village",
      currentVillageId: 0,
      currentBuildId: 0,
      currentLayerId: 0,
      currentRoomId: 0,
      currentParentRoomId: 0,
      // 更新树数据
      refreshTrigger: 0,
      refreshParams: {},

      // 选择项目类型
      chooseTypeVisible: false,
      // 添加楼宇
      buildingAddVisible: false,
      // 添加楼层
      layerAddVisible: false,
      // 导入房源
      importRoomVisible: false,
      // 新增房源
      addRoomVisible: false,
    });

    /** 监听数据修改触发的左侧树变化 */
    watch(
      () => store.getters.refreshTreeTrigger,
      () => {
        state.refreshParams = {
          ...store.getters.refreshTreeParams,
        };
        state.refreshTrigger++;
      }
    );
    const addTurnoverShow = computed(() => store.getters.showAddTurnover);

    watch(
      () => addTurnoverShow.value,
      (val) => {
        if (val) {
          if (state.currentRoomId) {
            // 选择房间
            request
              .get("/org", "/owner/ownerListByRoomId", {
                build_id: state.currentBuildId,
                room_id: state.currentRoomId,
              })
              .then((res) => {
                if (res.list && res.list.length > 0) {
                  store.commit("SET_ADD_TURNOVER_OWNER_ID", res.list[0].id);
                } else {
                  store.commit("SET_ADD_TURNOVER_OWNER_ID", 0);
                }
                store.commit("SET_ADD_TURNOVER_VISIBLE", true);
              });
          } else {
            store.commit("SET_ADD_TURNOVER_OWNER_ID", 0);
            store.commit("SET_ADD_TURNOVER_VISIBLE", true);
          }
        } else {
          store.commit("SET_ADD_TURNOVER_OWNER_ID", 0);
          store.commit("SET_ADD_TURNOVER_VISIBLE", false);
        }
      }
    );

    const onRoomClick = (item) => {
      console.log("item: ", item);
      item.extra = {
        village_id: item.village_id,
        build_id: item.build_id,
        layer_id: item.layer_id,
      };
      item.childType = "room";
      setCurrent(item);
    };

    /** 当前条目移除 */
    const onCurrentRemove = (type) => {
      if (type == "village") {
        state.refreshParams = { reset: true };
      } else if (type == "build") {
        state.refreshParams = {
          reset: true,
          selected: {
            villageId: state.currentVillageId,
          },
        };
      } else if (type == "layer") {
        state.refreshParams = {
          villageId: state.currentVillageId,
          buildId: state.currentBuildId,
          selected: {
            buildId: state.currentBuildId,
          },
        };
      } else if (type == "room") {
        state.refreshParams = {
          villageId: state.currentVillageId,
          buildId: state.currentBuildId,
          layerId: state.currentLayerId,
          selected: {
            layerId: state.currentLayerId,
          },
        };
      }
      state.refreshTrigger++;
    };

    /** 当前条目修改 */
    const onCurrentChange = (e) => {
      state.refreshParams = {
        changeCurrentName: e.name,
      };
      state.refreshTrigger++;
    };

    /** 编辑当前楼宇的楼层 */
    const onBuildLayerChange = () => {
      state.refreshParams = {
        villageId: state.currentVillageId,
        buildId: state.currentBuildId,
      };
      state.refreshTrigger++;
    };

    /** 获取树当前选中 */
    const getCurrentSelect = (info) => {
      console.log("info: ", info);
      setCurrent(info.current);
    };
    /** 租客画像选中 */
    const getCurrentRent = (info) => {
      console.log("info2: ", info);
      setCurrent(info.current);
    };
    // 当前选中
    const setCurrent = (current) => {
      state.currentSelect = current;
      state.currentType = current.childType;
      if (state.currentType == "village") {
        state.currentVillageId = current.id;
      } else {
        state.currentVillageId = current.extra.village_id;
        if (state.currentType == "build") {
          state.currentBuildId = current.id;
        } else {
          state.currentBuildId = current.extra.build_id;
          if (state.currentType == "layer") {
            state.currentLayerId = current.id;
          } else {
            state.currentLayerId = current.extra.layer_id;
            state.currentRoomId = current.id;

            // 子房间特殊处理
            state.currentParentRoomId = 0;
            if (current.parent_room_id) {
              state.currentParentRoomId = current.parent_room_id;
            }
          }
        }
      }
    };

    /** 添加楼层成功 */
    const handleLayerAddSuccess = () => {
      state.layerAddVisible = false;
      onBuildLayerChange();
    };

    /** 房源导入成功 */
    const importRoomSuccess = () => {
      state.importRoomVisible = false;
      state.refreshParams = {};
      state.refreshTrigger++;
    };

    /** 添加房源成功 */
    const handleRoomAddSuccess = () => {
      state.addRoomVisible = false;
      state.refreshParams = {
        villageId: state.currentVillageId,
        buildId: state.currentBuildId,
        layerId: state.currentLayerId,
      };
      state.refreshTrigger++;
    };

    /** 搜索房间 */
    const searchedListPagination = computed(() => ({
      total: state.searchedListTotal,
      current: state.searchedListPage,
      pageSize: state.searchedListPageSize,
      showSizeChanger: true,
      onChange: (page, pageSize) => {
        state.searchedListPage = page;
        state.searchedListPageSize = pageSize;
        onTreeSearch();
      },
      onShowSizeChange: (current, size) => {
        state.searchedListPage = current;
        state.searchedListPageSize = size;
        onTreeSearch();
      },
    }));
    const onTreeSearch = () => {
      if (state.treeSearchValue) {
        let params = {
          page: state.searchedListPage,
          pageSize: state.searchedListPageSize,
        };
        params[state.treeSelectSearchValue] = state.treeSearchValue;
        request
          .get("/village", "/houseResource/resourceList", { ...params })
          .then((res) => {
            state.showSearch = true;
            state.searchedList = res?.list || [];
            state.searchedListTotal = res?.total || 0;
          });
      } else {
        state.showSearch = false;
        state.searchedList = [];
      }
    };

    const $router = useRouter();
    // 新建项目
    const addVillage = () => {
      request.get("/village", "/village/type/list").then((res) => {
        if (res.list.length == 1) {
          $router.push({
            name: "projectEdit",
            query: { type: res.list[0].alias },
          });
        } else {
          state.chooseTypeVisible = true;
        }
      });
    };

    return {
      ...toRefs(state),
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      searchedListPagination,
      onTreeSearch,
      getCurrentSelect,
      getCurrentRent,
      handleLayerAddSuccess,
      importRoomSuccess,
      handleRoomAddSuccess,
      onCurrentRemove,
      onBuildLayerChange,
      onCurrentChange,
      onRoomClick,
      addVillage,
    };
  },
});
</script>

<style lang="less" scoped>
#managementCenter {
  width: 100%;
  height: 100%;

  .layout {
    width: 100%;
    height: 100%;

    .left {
      border-left: 1px solid #f0f0f0;
      background-color: #fff;
      height: 100%;
      overflow: hidden;
      padding: 8px;
      position: relative;
      .left-content {
        height: 100%;
        overflow: hidden auto;
      }
      .footer-btn {
        position: absolute;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: #fff;
        box-shadow: -2px 0px 8px 0px rgba(0, 0, 0, 0.1);
      }
    }

    .right {
      flex: 1;
      width: 100%;
      height: 100%;
      box-sizing: border-box;
      overflow: hidden;
      border-left: 1px solid #f1f1f1;
    }
  }

  .search-box {
    display: flex;
    :deep(.ant-select-selector) {
      border-bottom-right-radius: 0;
      border-top-right-radius: 0;
      border-right: none;
      padding: 0 5px;
    }
    .search-box-input {
      :deep(.ant-input-search) {
        border-radius: 0;
        padding: 4px;
      }
    }
  }

  .org-tree-dec {
    flex: 1;
    display: flex;
    flex-direction: column;
  }
}
</style>
